package com.gang.music.core.shiro;

import com.gang.music.core.interfaces.ShiroService;
import com.gang.music.system.entity.User;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Collections;
import java.util.List;

public class ShiroDbRealm extends AuthorizingRealm {
	
	@Autowired
	private ShiroService shiroService;

	/**
	 * 认证回调函数,登录时调用.
	 * 
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
		
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		
		User user = shiroService.user(token.getUsername());
		ShiroUser shiroUser = shiroService.shiroUser(user);
		SimpleAuthenticationInfo info = shiroService.info(shiroUser, user, getName());
		
		return info;
	}

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		
		ShiroUser shiroUser = (ShiroUser) principals.getPrimaryPrincipal();
		Long userId = shiroUser.getId();
		
		List<String> userRoleCodes = shiroService.findRolesByUserId(userId);
		List<String> userPermissions = shiroService.findPermissionsByUserId(userId);
		//去除null值元素
		userPermissions.removeAll(Collections.singleton(null));
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		
		info.addRoles(userRoleCodes);
		info.addStringPermissions(userPermissions);
		return info;
	}
}
